﻿using System;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq.Expressions;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;

namespace TS.Commons
{
    public static class Utility
    {
        public static string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
        {
            return (propertyExpression.Body as MemberExpression).Member.Name;
        }

        public static string ToStringOrDefault(this object value)
        {
            if (value == null || DBNull.Value == value) return string.Empty;
            return value.ToString();
        }

        public static int ToNumeric(this object value)
        {
            try
            {
                return Int32.Parse(value.ToStringOrDefault(), CultureInfo.CurrentCulture);
            }
            catch (OverflowException e)
            {
                Console.WriteLine(e.ToString());
            }
            catch (FormatException e)
            {
                Console.WriteLine(e.ToString());
            }
            return 0;
        }

        public static int ToBool(this object value)
        {
            try
            {
                if (value.ToStringOrDefault() == "1" || value.ToStringOrDefault()=="True")
                {
                    return 1;
                }
            }
            catch (OverflowException e)
            {
                Console.WriteLine(e.ToString());
            }
            catch (FormatException e)
            {
                Console.WriteLine(e.ToString());
            }
            return 0;
        }

        /// <summary>
        /// Convert to Datekey yyyymmdd
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static int ToDateKey(this object value)
        {
            try
            {
                string start = "";
                if (value.ToStringOrDefault().Length >= 8)
                {
                    var t = value.ToStringOrDefault().Split('/', '-');

                    if (t.Length == 3)
                    {
                        //year
                        if (t[2].ToStringOrDefault().Length == 4 && t[2].ToNumeric()>1979)
                            start = start + t[2].ToNumeric();
                        else return -1;

                        //Month
                        if (t[1].ToNumeric() >= 10 && t[1].ToNumeric() <= 12)
                            start = start + t[1].ToNumeric();
                        else
                            if (t[1].ToNumeric() > 0 && t[1].ToNumeric() <= 12)
                                start = start + "0" + t[1].ToNumeric();
                            else return -1;

                        //Day
                        if (t[0].ToNumeric() >= 10 && t[0].ToNumeric() <= 31)
                            start = start + t[0].ToNumeric();
                        else
                            if (t[0].ToNumeric() > 0 && t[0].ToNumeric() <= 31)
                                start = start + "0" + t[0].ToNumeric();
                            else return -1;
                        return start.ToNumeric();
                    }
                    else return -1;
                }
                else
                    if (value.ToStringOrDefault().Length == 0) return 0;
                    else return -1;
            }
            catch (FormatException e)
            {
                Console.WriteLine(e.ToString());
            }
            return -1;
        }

        /// <summary>
        /// MD5 Hash generator
        /// </summary>
        /// <param name="strSource"></param>
        /// <returns></returns>
        public static String GetMD5(String strSource)
        {
            var x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = Encoding.UTF8.GetBytes(strSource);
            bs = x.ComputeHash(bs);
            var s = new StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2", CultureInfo.CurrentCulture).ToLower(CultureInfo.CurrentCulture));
            }
            return s.ToString();
        }

        /// <summary>
        /// Check Valid Email
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public static bool IsValidEmail(string email)
        {
            if (!string.IsNullOrEmpty(email))
            {
                var emailregex = new Regex("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
                var m = emailregex.Match(email);
                return m.Success;
            }
            return false;
        }

        /// <summary>
        /// Send Email New Password
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        public static bool SendEmail(string from, string to, string subject, string body)
        {
            if (!string.IsNullOrEmpty(from)
                && !string.IsNullOrEmpty(to)
                && !string.IsNullOrEmpty(subject)
                && !string.IsNullOrEmpty(body))
            {
                var smtp = new SmtpClient();
                var msg = new MailMessage(from, to, subject, body);
                msg.IsBodyHtml = true;
                //SmtpClient smtpClient = new SmtpClient();
                smtp.EnableSsl = true;
                //smtp.Host = "smtp.gmail.com";//Sử dụng SMTP của gmail
                smtp.Send(msg);
                return true;
            }
            return false;
        }

        /// <summary>
        /// Gets the get password.
        /// </summary>
        /// <value>
        /// The get password.
        /// </value>
        public static string CreatePassword()
        {

            var builder = new StringBuilder();
            builder.Append(RandomString(4, true));
            builder.Append(RandomNumber(1000, 9999));
            builder.Append(RandomString(2, false));
            return builder.ToString();

        }

        /// <summary>
        /// Randoms the string.
        /// </summary>
        /// <param name="size">The size.</param>
        /// <param name="lowercase">if set to <c>true</c> [lowercase].</param>
        /// <returns></returns>
        public static string RandomString(int size, bool lowercase)
        {
            var builder = new StringBuilder();
            var random = new Random();
            for (int i = 0; i < size; i++)
            {
                char ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }
            if (lowercase)
                return builder.ToString().ToLower(CultureInfo.CurrentCulture);
            return builder.ToString();
        }

        /// <summary>
        /// Randoms the number.
        /// </summary>
        /// <param name="min">The min.</param>
        /// <param name="max">The max.</param>
        /// <returns></returns>
        public static int RandomNumber(int min, int max)
        {
            var random = new Random();
            return random.Next(min, max);
        }

        /// <summary>
        /// Writes the string.
        /// </summary>
        /// <param name="str">The STR.</param>
        /// <param name="length">The length.</param>
        /// <returns></returns>
        public static string WriteString(string str, int length)
        {
            int len = str.Length;
            if (len > length)
            {
                len = length;
                var newStr = str.Substring(0, len);
                string[] arr = newStr.Split(Convert.ToChar(" ", CultureInfo.CurrentCulture));
                newStr = "";
                for (int i = 0; i < arr.Length; i++)
                {
                    newStr += arr[i] + " ";
                }
                newStr += "...";
                return newStr;
            }
            return str;
        }
    }
}
